import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Row, Col, notification } from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { createRole, updateRole } from '@/services/role';
import { createMenu } from '@/services/menu';
import { mapData, delAuth } from '@/utils/utils';
import EditTree from '@/components/EditTree';
import { queryMenu } from '@/services/menu';
import { history, useLocation } from 'umi';

import type { RoleCreateProps } from './src/data';
import type { EditTreeType } from '@/components/EditTree/data';

const RoleCreate: React.FC<RoleCreateProps> = () => {
  const [treeData, setTreeData] = useState<EditTreeType[]>([]);
  const [expandedKeyArr, setExpandedKeyArr] = useState<string[]>([]);
  const [checkVal, setCheckVal] = useState<string[]>([]);
  const [title, setTitle] = useState<string>('创建角色');
  const [form] = ProForm.useForm();
  const location: any = useLocation<any>();

  const reduceCheck = (key: string, data: EditTreeType[], authorName: string) => {
    data.forEach((item: EditTreeType) => {
      if (item.key === key) {
        if (item.authority) {
          // 没有才push
          if (item.authority?.indexOf(authorName) === -1) {
            item.authority?.push(authorName);
          }
        } else {
          // eslint-disable-next-line no-param-reassign
          item.authority = [authorName];
        }
      }
      if (item.children) {
        reduceCheck(key, item.children, authorName);
        // if (item.parentKey) {
        //   reduceCheck(item.parentKey, data, authorName);
        // }
      }
    });
  };

  const handleFormSumbit = async (values: any) => {
    if (location?.query?.type === 'edit') {
      delAuth(treeData, location?.state?.name);
    }
    checkVal.forEach((item: string) => {
      reduceCheck(item, treeData, values.name);
    });
    const menuData = mapData(treeData);
    const resMenu = await createMenu({ menuData });
    if (resMenu) {
      if (location?.query?.type === 'edit') {
        const resRole = await updateRole({
          name: location?.state?.name,
          updateName: values.name,
        });
        if (resRole) {
          notification.success({
            message: resRole.message,
          });
          history.push('/manager/roleManager/find');
        }
      } else {
        const resRole = await createRole(values);
        if (resRole) {
          notification.success({
            message: resRole.message,
          });
          history.push('/manager/roleManager/find');
        }
      }
    }
  };

  // 默认全部展开
  const reducerExpendKey = (data: EditTreeType[], tempArr: string[]) => {
    data?.forEach((item: EditTreeType) => {
      tempArr.push(item.key as string);
      if (item.children) {
        reducerExpendKey(item.children, tempArr);
      }
    });
  };

  useEffect(() => {
    const getTreeData = async () => {
      const res = await queryMenu();
      if (res) {
        setTreeData(res.data?.menuData);
        // 默认菜单全部展开
        const keyArr: string[] = [];
        reducerExpendKey(res.data?.menuData, keyArr);
        setExpandedKeyArr(keyArr);
      }
      if (location?.query?.type === 'edit') {
        setTitle('编辑角色');
        form.setFieldsValue({
          name: location?.state?.name,
        });
      }
    };
    getTreeData();
  }, []);

  const onCheck = (checkedKeysValue: any, e: any) => {
    // 选中与半选中，且去重
    setCheckVal(Array.from(new Set(checkedKeysValue.concat(e.halfCheckedKeys))));
  };

  return (
    <PageContainer className="role_create">
      <Card>
        <h3>{title}</h3>
        <ProForm layout="horizontal" onFinish={handleFormSumbit} form={form}>
          <ProFormText
            width="md"
            name="name"
            label="角色名称"
            placeholder="请输入角色名称"
            rules={[
              {
                required: true,
                message: '角色名不能为空',
              },
            ]}
          />
          <Row justify="start">
            <Col>用户权限：</Col>
            <Col>
              <EditTree
                checkable
                expandedKeyArr={expandedKeyArr}
                editTreeData={treeData}
                onCheck={onCheck}
                getTreeDate={() => {}}
              />
            </Col>
          </Row>
        </ProForm>
      </Card>
    </PageContainer>
  );
};

export default RoleCreate;
